package com.gdcp.controller.portal;

import com.alibaba.fastjson.JSONObject;
import com.gdcp.beans.*;
import com.gdcp.common.ResponseModel;
import com.gdcp.config.RequestHolder;
import com.gdcp.config.annotation.CategoryByAll;
import com.gdcp.common.page.PageBean;
import com.gdcp.config.annotation.RedisCache;
import com.gdcp.service.*;
import com.gdcp.util.FileUtil;
import com.gdcp.util.GetPcUtil;
import com.gdcp.util.HttpServletRequestUtil;
import com.gdcp.util.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

/**
 * @author 杨华京
 * @version 1.0
 * @description
 * @since 1.8
 */
@Controller
@RequestMapping("/render/product/")
public class ProductController {

    @Autowired
    ResponseModel responseModel;
    @Autowired
    ProductService productService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    BannerService bannerService;
    @Autowired
    CommentService commentService;
    @Autowired
    ShopService shopService;
    @Autowired
    UserService userService;
    @Autowired
    NewsService newsService;
    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping(value = "/index",method = RequestMethod.GET)
    @CategoryByAll(flush = true)
    public String index(){
        List<Banner> banner = bannerService.queryByStatus();
        List<Product> product_createTime = productService.queryByCreateTime();
        List<Product> product_popularity = productService.queryByPopularity();
        List<Product> product_sale_count = productService.queryBySale_count();
        HttpServletRequest request = RequestHolder.getRequest();
        request.setAttribute("banners",banner);
        request.setAttribute("product_popularity",product_popularity);
        request.setAttribute("product_sale_count",product_sale_count);
        request.setAttribute("productCreateTime",product_createTime);



        List<List<Product>> productList=new ArrayList<>();
        List<List<Product>> listProduct=new ArrayList<>();
        List<Category> categories= (List<Category>) RequestHolder.getSession("categoryByAll");
        for (Category category:categories){
            if (category.getParent_id()==1){
                int count=1;
                List<Product> productList1=new ArrayList<>();
                //List<Category> categories1=categoryService.queryByParentId(category.getId());-----查询二级分类
                for (Category category1:categories){
                    if (category.getId().equals(category1.getParent_id())) {
                        List<Product> productList2=new ArrayList<>();
                        //for、if等于categoryService.queryByParentId
                        for (Category category2:categories) {
                            if (category1.getId().equals(category2.getParent_id())) {
                                List<Product> products = productService.queryProductsByCid(category2.getId());
                                if (count==1) {
                                    listProduct.add(products);
                                    System.out.println(products);
                                    count++;
                                }
                                if (products != null) {
                                    productList2.addAll(products);
                                }
                            }
                        }
                        //add()方法是向原有的list中添加对象（作为整体）
                        //addAll()方法是按照位置逐条向原有的list中添加对象元素
                        productList1.addAll(productList2);
                    }
                }

                productList1.sort((o1, o2) -> {
                    try {
                        int dt1 = o1.getPopularity();
                        int dt2 = o2.getPopularity();

                        return Long.compare(dt2, dt1);
                    } catch (Exception e) {
                        System.out.println("排列时间报错" + e);
                    }
                    return 0;
                });
                productList.add(productList1);
            }
        }

        request.setAttribute("listProduct",listProduct);
        request.setAttribute("productList",productList);

        List<Shop> shops=shopService.queryByNewTime();
        for (Shop shop:shops){
            User user=userService.getInformation(shop.getUser_id());
            if(user!=null) {
                shop.setUser_image(user.getImage());
                if(user.getImage()!=null) {
                    shop.setUser_image(user.getImage());
                }
                //else {
                    //shop.setUser_image("");
                //}
            }
            //else {
                //shop.setUser_image("");
            //}
        }

        List<News> newsList=newsService.queryByLimit();
        request.setAttribute("shopNewTime",shops);
        request.setAttribute("newsList",newsList);

        return "frontend/index";
    }

    /*@RequestMapping(value = "/getProducts",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getProducts(Integer parent_id, Integer curPage){
        int pageSize=16;
        int startRow = (curPage - 1) * pageSize;

        List<Product> products=productService.queryByLimit(parent_id,startRow,pageSize);

        RequestHolder.getRequest().setAttribute("products",products);
        RequestHolder.getRequest().setAttribute("curPage",curPage);
        return null;
    }*/

    //大H,时间戳
    @RequestMapping(value = "/getProductsByCid",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getProductsByCid(Integer category_id){
        List<Product> products=productService.queryProductsByCid(category_id);
        return responseModel.setModel(true,products);
    }

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @CategoryByAll(flush = true)
    public String list(){
        //搜索该分类的子类，写在左侧。
        HttpServletRequest request = RequestHolder.getRequest();
        comment(request);
        Boolean flag=categoryIsAll(request);

        if (!flag){
            return "frontend/index";
        }

        List<Product> product_sale_count = productService.queryBySale_count();
        request.setAttribute("product_sale_count",product_sale_count);
        return "frontend/list";
    }

    @RequestMapping(value = "/search",method = RequestMethod.GET)
    @CategoryByAll(flush = true)
    public String search() {
        HttpServletRequest request = RequestHolder.getRequest();
        comment(request);
        /*Integer key = Integer.valueOf(request.getParameter("key"));
        if (key==0) {
            Boolean flag = categoryIsAll(request);
            if (!flag){
                return "frontend/index";
            }
        }*/

        List<Product> product_sale_count = productService.queryBySale_count();
        request.setAttribute("product_sale_count", product_sale_count);

        return "frontend/list";
    }

    //@PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @RequestMapping(value = "/product_detail",method = RequestMethod.GET)
    @CategoryByAll(flush = true)
    public String productDetail() {
        HttpServletRequest request = RequestHolder.getRequest();

        Integer id = HttpServletRequestUtil.getInt(request,"id");
        if (id==-1){
            return "frontend/index";
        }

        Product product=productService.productInfoById(id);
        //查询该商品下的评论
        List<Comment> comments=commentService.queryListByProductId(id);
        //因为评论分为两层（第一层为评论，第二次为店家回复）
        for (Comment comment:comments){
            Comment comment_info=commentService.queryInfoByParentId(comment.getId());
            if (comment_info!=null){
                comment.setReply(comment_info.getContent());
            }
        }
        Shop shop=shopService.queryShopInfoByShopId(product.getShop_id());
        productService.updatePopularity(product.getId());
        request.setAttribute("shop",shop);
        //获取三视图
        if (product.getSub_images().indexOf('\\')>0) {
            String json = product.getSub_images().replaceAll("\\\\", "\\\\\\\\");
            JSONObject jsonObj = JSONObject.parseObject(json);
            request.setAttribute("image_left",jsonObj.getString("image_left"));
            request.setAttribute("image_center",jsonObj.getString("image_center"));
            request.setAttribute("image_right",jsonObj.getString("image_right"));
        }

        product.setDetail(FileUtil.readWord(product.getDetail()));
        request.setAttribute("product",product);
        request.setAttribute("comments",comments);

        List<Product> product_sale_count = productService.queryBySale_count();
        request.setAttribute("product_sale_count",product_sale_count);
        return "frontend/product_info";
    }

    private void comment(HttpServletRequest request){
        //当前页码
        int pc = GetPcUtil.getPc(request);
        //分类的id
        Integer cid = HttpServletRequestUtil.getInt(request,"id");
        //关键字
        String sort = request.getParameter("sort");
        Integer key = Integer.valueOf(request.getParameter("key"));


        //获取开始价格>
        String min = HttpServletRequestUtil.getString(request,"min");
        //System.out.println("min="+min);
        //获取结束价格<
        String max = HttpServletRequestUtil.getString(request,"max");

        Integer pmin=null;
        if (min!=null&&!min.equals("")){
            pmin= Integer.valueOf(min);
        }
        Integer pmax=null;
        if (max!=null&&!max.equals("")){
            pmax= Integer.valueOf(max);
        }

        //搜索
        if (cid==0){
            //分类的id
            String search_key = request.getParameter("search_key");

            Map<String, Object> map=handleSort(sort);

            //搜索商品
            if (key==0){

                PageBean<Product> pb = productService.searchByKeyWord(cid, pc, search_key, (String)map.get("column"),
                        (String)map.get("sort"), pmin, pmax);
                //System.out.println(pb.getTp());
                request.setAttribute("pb",pb);
                request.setAttribute("cid",cid);
                request.setAttribute("sort",sort);
                request.setAttribute("key",key);
                request.setAttribute("search_key",search_key);
                request.setAttribute("min",pmin);
                request.setAttribute("max",pmax);
            }

            //搜索店铺
            if (key==1){
                PageBean<Shop> pb = shopService.searchByShop(cid, pc, search_key, (String)map.get("column"), (String)map.get("sort"));
                for (Shop shop:pb.getBeanList()){
                    User user=userService.getInformation(shop.getUser_id());
                    shop.setUser_image(user.getImage());
                }
                //System.out.println(pb.getTp());
                request.setAttribute("pb_shop",pb);
                request.setAttribute("cid",cid);
                request.setAttribute("sort",sort);
                request.setAttribute("key",key);
                request.setAttribute("search_key",search_key);
            }
        }
        //点击分类
        else{
            Map<String, Object> map=handleSort(sort);
            PageBean<Product> pb = productService.findByKeyWord(cid, pc, (String)map.get("column"), (String)map.get("sort"), pmin, pmax);
            request.setAttribute("pb",pb);
            request.setAttribute("cid",cid);
            request.setAttribute("sort",sort);
            request.setAttribute("key",key);
            request.setAttribute("min",pmin);
            request.setAttribute("max",pmax);
        }
    }

    private Boolean categoryIsAll(HttpServletRequest request){
        Integer cid= HttpServletRequestUtil.getInt(request,"id");
        //System.out.println("cid="+cid);
        List<Category> categories=categoryService.queryById(cid);
        //System.out.println("categories="+categories);
        if (categories.size()>0){
            request.setAttribute("categories",categories);
            //该分类的信息
            Category category = categoryService.getInformation(cid);
            request.setAttribute("category", category);
            //如果是最低的子类，那就搜索它的兄弟父类
        }else {
            if (request.getParameter("parent_id")!=null){
                Integer parent_id= Integer.valueOf(request.getParameter("parent_id"));
                List<Category> categories_parent=categoryService.queryById(parent_id);
                request.setAttribute("categories",categories_parent);
                request.setAttribute("parent_id",parent_id);
                //该分类的信息
                Category category = categoryService.getInformation(parent_id);
                request.setAttribute("category", category);
            }else{
                return false;
            }
        }

        return true;
    }

    private Map<String, Object> handleSort(String keyword){
        Map<String, Object> modelMap=new HashMap<>();
        keyword = (keyword==null)?"":keyword;
        String column;
        //降序
        String sort = "desc";
        switch(keyword){
            //销量
            case "sale_count":
                column = "sale_count";
                break;
            //人气
            case "popularity":
                column = "popularity";
                break;
            //信用
            case "credit":
                column = "credit";
                break;
            //价格
            case "price":
                column = "price";
                break;
            //价格
            case "priceInverse":
                column = "price";
                sort = "asc";
                break;
            //默认
            default:
                column = null;
                break;
        }
        modelMap.put("column",column);
        modelMap.put("sort",sort);
        return modelMap;
    }
}
